<div style="margin-bottom: 10px;">
    <button id="batchCreateTaskBtn" class="layui-btn layui-btn-normal">批量创建任务</button>
</div>

<script>
    function batchCreateTaskFunc($, table, layer, form, laydate) {
        // 实现批量创建任务的逻辑
        // 监听批量创建任务按钮点击事件
        $('#batchCreateTaskBtn').on('click', function () {
            var checkStatus = table.checkStatus('Index-ID-table-demo-page');
            var data = checkStatus.data;

            if (data.length === 0) {
                layer.msg('请至少选择一项任务作为模板', { icon: 5 });
                return;
            }

            // 打开批量创建任务弹窗
            var index = layer.open({
                type: 1,
                title: '批量创建任务',
                content: `
                    <div style="padding: 20px;">
                        <div class="layui-form-item">
                            <label class="layui-form-label">创建数量</label>
                            <div class="layui-input-block">
                                <input type="number" id="batchCreateCount" lay-verify="required|number" placeholder="请输入要创建的任务数量" class="layui-input" min="1" value="1">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">任务命名</label>
                            <div class="layui-input-block">
                                <select id="batchCreateNameType">
                                    <option value="1">原名称+序号</option>
                                    <option value="2">统一前缀+序号</option>
                                </select>
                            </div>
                        </div>
                        <div class="layui-form-item" id="batchCreatePrefixDiv" style="display: none;">
                            <label class="layui-form-label">统一前缀</label>
                            <div class="layui-input-block">
                                <input type="text" id="batchCreatePrefix" placeholder="请输入统一前缀" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">任务状态</label>
                            <div class="layui-input-block">
                                <select id="batchCreateStatus">
                                    <option value="1">未开始</option>
                                    <option value="2">进行中</option>
                                </select>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">时间设置</label>
                            <div class="layui-input-block">
                                <select id="batchCreateTimeType">
                                    <option value="1">使用原任务时间</option>
                                    <option value="2">设置统一时间</option>
                                </select>
                            </div>
                        </div>
                        <div id="batchCreateTimeDiv" style="display: none;">
                            <div class="layui-form-item">
                                <label class="layui-form-label">开始时间</label>
                                <div class="layui-input-block">
                                    <input type="text" id="batchCreateStartTime" placeholder="YYYY-MM-DD HH:mm:ss" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">结束时间</label>
                                <div class="layui-input-block">
                                    <input type="text" id="batchCreateEndTime" placeholder="YYYY-MM-DD HH:mm:ss" class="layui-input">
                                </div>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <div class="layui-input-block">
                                <span class="layui-badge layui-bg-gray">已选择 ${data.length} 个任务作为模板</span>
                            </div>
                        </div>
                    </div>
                `,
                area: ['600px', 'auto'],
                btn: ['确定创建', '取消'],
                success: function (layero) {
                    // 初始化下拉框
                    form.render('select');

                    // 监听命名方式变化
                    $('#batchCreateNameType').on('change', function () {
                        if ($(this).val() === '2') {
                            $('#batchCreatePrefixDiv').show();
                        } else {
                            $('#batchCreatePrefixDiv').hide();
                        }
                    });

                    // 监听时间设置方式变化
                    $('#batchCreateTimeType').on('change', function () {
                        if ($(this).val() === '2') {
                            $('#batchCreateTimeDiv').show();

                            // 初始化日期时间选择器
                            laydate.render({
                                elem: '#batchCreateStartTime',
                                type: 'datetime',
                                format: 'yyyy-MM-dd HH:mm:ss',
                                min: 0,
                                trigger: 'click'
                            });

                            laydate.render({
                                elem: '#batchCreateEndTime',
                                type: 'datetime',
                                format: 'yyyy-MM-dd HH:mm:ss',
                                min: 0,
                                trigger: 'click'
                            });
                        } else {
                            $('#batchCreateTimeDiv').hide();
                        }
                    });
                },
                yes: function (index) {
                    // 获取表单数据
                    var count = parseInt($('#batchCreateCount').val());
                    var nameType = $('#batchCreateNameType').val();
                    var prefix = $('#batchCreatePrefix').val();
                    var status = parseInt($('#batchCreateStatus').val());
                    var timeType = $('#batchCreateTimeType').val();
                    var startTime = $('#batchCreateStartTime').val();
                    var endTime = $('#batchCreateEndTime').val();

                    // 验证表单
                    if (isNaN(count) || count < 1) {
                        layer.msg('请输入有效的创建数量', { icon: 5 });
                        return;
                    }

                    if (nameType === '2' && (!prefix || prefix.trim() === '')) {
                        layer.msg('请输入统一前缀', { icon: 5 });
                        return;
                    }

                    if (timeType === '2') {
                        if (!startTime) {
                            layer.msg('请输入开始时间', { icon: 5 });
                            return;
                        }
                        if (!endTime) {
                            layer.msg('请输入结束时间', { icon: 5 });
                            return;
                        }
                        if (new Date(startTime) >= new Date(endTime)) {
                            layer.msg('结束时间必须晚于开始时间', { icon: 5 });
                            return;
                        }
                    }

                    // 显示加载中
                    var loadingIndex = layer.load(2, {
                        shade: [0.3, '#393D49']
                    });

                    // 批量创建任务
                    var successCount = 0;
                    var failCount = 0;
                    var totalTasks = data.length * count;
                    var completedTasks = 0;

                    // 更新加载提示
                    function updateLoadingMessage() {
                        if (completedTasks > 0) {
                            layer.msg(`正在创建任务 ${completedTasks}/${totalTasks}`, { icon: 16, time: 0 });
                        }
                    }

                    // 创建任务的函数
                    function createTask(taskData, indexSuffix) {
                        // 准备任务数据
                        var newTaskData = {
                            name: nameType === '1' ? `${taskData.name}-${indexSuffix}` : `${prefix}-${indexSuffix}`,
                            description: taskData.description,
                            status: status,
                            points: taskData.points,
                            start_time: timeType === '1' ? taskData.start_time : startTime,
                            end_time: timeType === '1' ? taskData.end_time : endTime
                        };

                        // 调用创建任务API
                        return axios({
                            url: '/api/task/create_task/',
                            method: 'POST',
                            data: newTaskData
                        }).then(function (res) {
                            res = res.data;
                            if (res.code === 0) {
                                successCount++;
                            } else {
                                failCount++;
                            }
                        }).catch(function (error) {
                            console.error('创建任务失败:', error);
                            failCount++;
                        }).finally(function () {
                            completedTasks++;
                            updateLoadingMessage();
                        });
                    }

                    // 收集所有创建任务的Promise
                    var promises = [];
                    for (var i = 0; i < data.length; i++) {
                        for (var j = 0; j < count; j++) {
                            var indexSuffix = (i * count + j + 1);
                            promises.push(createTask(data[i], indexSuffix));
                        }
                    }

                    // 等待所有任务创建完成
                    Promise.all(promises).then(function () {
                        layer.close(loadingIndex);
                        layer.close(index);

                        // 显示创建结果
                        layer.msg(`批量创建完成：成功 ${successCount} 个，失败 ${failCount} 个`, { icon: 6 });

                        // 刷新表格
                        table.reload('Index-ID-table-demo-page');
                    }).catch(function (error) {
                        layer.close(loadingIndex);
                        layer.close(index);
                        console.error('批量创建任务失败:', error);
                        layer.msg('批量创建过程中发生错误', { icon: 5 });

                        // 刷新表格
                        table.reload('Index-ID-table-demo-page');
                    });
                }
            });


        });

    }
</script>